<?php
declare(strict_types=1);

namespace Zms\Request;

use Zms\Unit\Xml;

class Result
{
    /**
     * HTTP响应码
     * @var int
     */
    protected $_code = 0;

    /**
     * 系统错误信息
     * @var string
     */
    protected $_message = '';

    /**
     * 请求结果
     * @var string|null
     */
    protected $_body = null;


    /**
     * @var string 驱动类型
     */
    protected $_driver = Http::CURL;


    /**
     * @param int $code 请求状态码
     * @param string $message 请求消息
     * @param string|null $body 相应信息
     */
    public function __construct($code = 0, $message = '', $body = null, $_driver = Http::CURL)
    {
        $this->_code = max(0, $code);//负号状态归到失败0
        $this->_message = $message;
        $this->_body = $body;
        $this->_driver = $_driver;
    }

    /**
     * @describe 请求响应码
     * @user zlf <zms-pro@qq.com> 2025/3/13
     * @return int
     */
    public function getCode(): int
    {
        return $this->_code;
    }


    /**
     * @describe 获取消息内容
     * @user zlf <zms-pro@qq.com> 2025/3/13
     * @return string|null
     */
    public function getMessage()
    {
        return $this->_message;
    }


    /**
     * @describe 获取响应内容
     * @user zlf <zms-pro@qq.com> 2025/3/13
     * @return string|null
     */
    public function getBody()
    {
        return $this->_body;
    }


    /**
     * @describe 获取驱动类型
     * @user zlf <zms-pro@qq.com> 2025/3/14
     * @return string
     */
    public function getDriver(): string
    {
        return $this->_driver;
    }


    /**
     * @describe 请求数据获取为JSON
     * @user zlf <zms-pro@qq.com> 2025/3/13
     * @return array|null
     */
    public function jsonToArray()
    {
        //请求的内容无效则返回null
        if (!($this->_code && $this->_body)) {
            return null;
        }
        if (function_exists('json_validate')) {//有内置函数用内置函数
            if (json_validate($this->_body)) {
                return json_decode($this->_body, true);//检验通过,返回序列
            }
        } else {
            $data = json_decode($this->_body, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                return $data;//校验通过，返回内容
            }
        }
        return null;
    }


    /**
     * @describe xml转数组
     * @user zlf <zms-pro@qq.com> 2025/3/14
     * @return array|null
     */
    public function xmlToArray()
    {
        if (!($this->_code && $this->_body)) {
            return null;
        }
        $result = Xml::toArray($this->_body);
        return empty($result) ? null : $result;
    }
}